package own.stu.jobgib.playown.alg.unionFind;

public class UnionFind_V1 {

    private int[] ids;

    private int count;

    public UnionFind_V1(int n) {

        count = n;
        ids = new int[n];
        for (int i = 0; i < n; i++) {
            ids[i] = i;
        }
    }

    private int find(int p) {
        return ids[p];
    }

    // 查看元素p和元素q是否所属一个集合
    // O(1)复杂度
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    // 合并元素p和元素q所属的集合
    // O(n) 复杂度
    public void union(int p, int q) {
        int pId = find(p);
        int qId = find(q);

        if (pId == qId) {
            return;
        }

        for (int i = 0; i < count; i++) {
            if (ids[i] == pId) {
                ids[i] = qId;
            }
        }
    }

}
